package net.office.controller;

import net.office.bean.SignIn;
import net.office.bean.StaffInfo;
import net.office.bean.WorkTable;
import net.office.service.SignInService;
import net.office.service.WorkTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class SignInController {

    @Autowired
    private SignInService signInService;

    @Autowired
    private WorkTableService workTableService;

    @RequestMapping("/sign/list.do")
    public String list(HttpSession session, Model model){

        StaffInfo staffInfo = (StaffInfo) session.getAttribute("staff");

        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();

        List<SignIn> signInList = signInService.findMonthByStaffId(staffInfo.getStaffId(), date);

        model.addAttribute("signInList", signInList);
        model.addAttribute("year", calendar.get(Calendar.YEAR));
        model.addAttribute("month", calendar.get(Calendar.MONTH)+1);
        return "sign";
    }

    @RequestMapping("/sign/update.do")
    @ResponseBody
    public Object signUpdate(HttpSession session){

        Map<String, String> map = new HashMap<String, String>();

        StaffInfo staffInfo = (StaffInfo) session.getAttribute("staff");

        Date signDate = new Date();
        SignIn signIn = new SignIn();
        signIn.setSignDate(signDate);
        signIn.setSignStaffId(staffInfo.getStaffId());
        int sign_res = signInService.insert(signIn);

        List<WorkTable> workTableList = workTableService.findOneByDate(staffInfo.getStaffId(), signDate);

        if(workTableList.size() != 0){
            for(int i=0; i<workTableList.size(); i++){
                workTableList.get(i).setIsWork("1");
            }
        }
        int work_res = workTableService.updateByPrimaryKey(workTableList);

        if(sign_res > 0 && work_res > 0){
            map.put("res", "1");
        }else{
            map.put("res", "0");
        }
        return map;
    }
}
